/*
Date:20220226 23:42PM
key:句子开始的前后都有空格太恶心了。特别注意去空格函数在面临全部空格时的提前跳出。
*/
class Solution {
public:
    void reverse(vector<string>&v,int l,int r) {
        while(l<=(l+r)/2)
        {
            swap(v[l],v[r]);
            l++;r--;
        }
    }
    string delespace(string s)
    {
       
        int l=0,r=s.size()-1;
        while(s[l]==' ')
        {
            l++;
        }
        if(l>r){return "";}
        while(s[r]==' ')
        {
            r--;
        }
        string s1;
        s1.resize(r-l+1);
        
        for(int i=l;i<=r;i++)
        {
            //cout<<s[i-l];
            s1[i-l]=s[i];
        }
        return s1;
    }
    string reverseWords(string s) {
        if(s.size()==0){return s;}
        vector<string>v;
        s=delespace(s);
        if(s.size()==0){return s;}
        string news="";
        string tmp="";
        for(int i=0;i<s.size();i++)
        {
            if(s[i]!=' ')
            {
                tmp=tmp+s[i];
                //cout<<tmp<<" ";
            }
            else
            {
                if(s[i+1]==' '){continue;}
                else
                {
                    
                    //reverseOneWords(tmp,0,tmp.size()-1);
                    //news=news+tmp;
                    v.push_back(tmp);
                    tmp="";
                }
            }
        }
        //cout<<tmp;
        v.push_back(tmp);
        reverse(v,0,v.size()-1);
        for(auto a:v)
        {
            news=news+' '+a;
        }
        news=delespace(news);
        return news;
    }
};